package com.example.xiaolu.utils;

import com.example.xiaolu.model.domain.User;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class TransferBase64 {
    private static final String relativePath = "src/main/resources/static/userAvatar";
    /**
     * 写入字符串数据到文件
     * @param data 要写入的字符串数据
     */
    public static void writeStringToFile(String data, String userId) {
        String path = relativePath + "/" + userId + "avatar.txt";
        try {
            Files.createDirectories(Paths.get(new File(path).getParent()));
            System.out.println(Files.write(Paths.get(path), data.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 从文件中读取字符串数据
     * @return 读取的字符串数据
     */
    public static String readStringFromFile(String userId) {
        String path = relativePath + "/" + userId + "avatar.txt";
        try {
            // 从文件中读取数据
            byte[] bytes = Files.readAllBytes(Paths.get(path));
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static User changeUserAvatar(User user) {
        writeStringToFile(user.getAvatarUrl(),user.getId()+"");
        user.setAvatarUrl(user.getId()+"");
        return user;
    }
    public static User getAvtar(User user) {
        user.setAvatarUrl(readStringFromFile(user.getId()+""));
        return user;
    }
}
